import uuid
from datetime import timedelta

from django.db import models

class Image(models.Model):
    image_id = models.AutoField(primary_key=True)
    image_data = models.BinaryField(null=False, help_text="图片二进制数据")
    mime_type = models.CharField(
        max_length=20,
        choices=[('image/jpeg', 'JPEG'), ('image/png', 'PNG'), ('image/webp', 'WebP')],
        default='image/jpeg',
        help_text="图片 MIME 类型"
    )

    def __str__(self):
        return f"Image {self.image_id}: {self.mime_type}"


class User(models.Model):
    ROLE_CHOICES = [
        ('customer', '普通顾客'),
        ('merchant', '商家'),
        ('admin', '管理员'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    wechat_openid = models.CharField(max_length=28, unique=True, null=True, blank=True)  # 微信 OpenID
    username = models.CharField(max_length=64)  # 昵称
    phone = models.CharField(max_length=11, unique=True)  # 手机号
    password_hash = models.CharField(max_length=120, null=True, blank=True)  # 密码哈希
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='customer')  # 角色
    created_at = models.DateTimeField(auto_now_add=True)  # 注册时间

    def __str__(self):
        return self.username

class MerchantInfo(models.Model):
    merchant_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    shop_name = models.CharField(max_length=100, unique=True, help_text="商家门店的公开显示名称")
    location = models.CharField(max_length=255, help_text="商家门店的公开地址")
    business_hours = models.CharField(max_length=255, null=True, blank=True, help_text="商家营业时间配置")
    contact_info = models.CharField(max_length=255, help_text="商家联系方式信息")
    introduction = models.TextField(
        null=True,
        blank=True,
        help_text="商家自我介绍，用于展示门店特色、服务内容或品牌故事"
    )
    register_time = models.DateTimeField(auto_now_add=True, help_text="商家首次注册的时间戳")

    def __str__(self):
        return self.shop_name

class MerchantImage(models.Model):
    merchant = models.ForeignKey(
        'MerchantInfo',
        on_delete=models.CASCADE,
        related_name='merchant_images',
        help_text="所属商家"
    )
    image = models.ForeignKey(
        'Image',
        on_delete=models.CASCADE,
        related_name='merchant_images',
        help_text="关联的图片资源"
    )
    sort_order = models.SmallIntegerField(
        default=0,
        help_text="控制图片展示顺序，值越小越靠前"
    )
    is_cover = models.BooleanField(
        default=False,
        help_text="是否为封面图，同一商家最多一个 TRUE"
    )

    class Meta:
        unique_together = ('merchant', 'image')  # 联合唯一约束
        ordering = ['sort_order']  # 默认按排序序号升序排列

    def __str__(self):
        return f"Merchant {self.merchant.shop_name} Image {self.image.image_id}"


from django.db import models
import uuid

class Category(models.Model):
    category_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    merchant = models.ForeignKey(
        'MerchantInfo',
        on_delete=models.CASCADE,
        related_name='categories',
        help_text="分类所属商家"
    )
    category_name = models.CharField(
        max_length=20,
        help_text="分类的显示名称，同一商家下唯一"
    )
    sort_order = models.SmallIntegerField(
        default=100,
        help_text="控制前端列表中分类的排列顺序，值越小越靠前"
    )

    class Meta:
        unique_together = ('merchant', 'category_name')  # 联合唯一约束

    def __str__(self):
        return f"{self.category_name} (Merchant: {self.merchant.shop_name})"


class Dish(models.Model):
    STATUS_CHOICES = [
        ('on_shelf', '上架'),
        ('off_shelf', '下架'),
    ]

    dish_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    merchant = models.ForeignKey(
        'MerchantInfo',
        on_delete=models.CASCADE,
        related_name='dishes',
        help_text="菜品所属商家"
    )
    category = models.ForeignKey(
        'Category',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='dishes',
        help_text="菜品的所属类别"
    )
    dish_name = models.CharField(max_length=50, help_text="菜品的显示名称")
    price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="菜品的当前售卖单价"
    )
    customization_options = models.JSONField(
        null=True,
        blank=True,
        help_text="用户可选的定制化参数"
    )
    sort_order = models.SmallIntegerField(
        default=100,
        help_text="控制前端列表中菜品的排列顺序，值越小越靠前"
    )
    stock = models.PositiveIntegerField(
        default=0,
        help_text="可用库存量（按份计算）"
    )
    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='on_shelf',
        help_text="控制菜品是否上架"
    )

    class Meta:
        ordering = ['sort_order']  # 默认按排序序号升序排列

    def save(self, *args, **kwargs):
        # 当库存为 0 时，自动下架
        if self.stock == 0:
            self.status = 'off_shelf'
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.dish_name} (Price: ¥{self.price}, Stock: {self.stock})"

class DishImage(models.Model):
    dish = models.ForeignKey(
        'Dish',
        on_delete=models.CASCADE,
        related_name='images',
        help_text="关联的菜品"
    )
    image = models.ForeignKey(
        'Image',
        on_delete=models.CASCADE,
        related_name='dish_images',
        help_text="关联的图片资源"
    )
    sort_order = models.SmallIntegerField(
        default=0,
        help_text="控制图片展示顺序，值越小越靠前"
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="图片上传的时间戳"
    )

    class Meta:
        unique_together = ('dish', 'image')  # 联合唯一约束
        ordering = ['sort_order']  # 默认按排序序号升序排列

    def __str__(self):
        return f"Image {self.image.image_id} for Dish {self.dish.dish_name}"

class Order(models.Model):
    STATUS_CHOICES = [
        ('pending_payment', '待支付'),
        ('in_preparation', '制作中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),

    ]

    order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        'User',
        on_delete=models.CASCADE,
        related_name='orders',
        help_text="下单用户"
    )
    merchant = models.ForeignKey(
        'MerchantInfo',
        on_delete=models.CASCADE,
        related_name='orders',
        help_text="接单商家"
    )
    table_number = models.CharField(
        max_length=10,
        null=True,
        blank=True,
        help_text="用户就餐的物理桌台编号"
    )
    total_amount = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="订单应付总价"
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending_payment',
        help_text="订单生命周期状态"
    )
    create_time = models.DateTimeField(auto_now_add=True, help_text="订单生成时间戳")
    rating = models.DecimalField(
        max_digits=2,
        decimal_places=1,
        default=0,
        help_text="用户对订单的综合评价分数"
    )
    comment = models.TextField(null=True, blank=True, help_text="用户对订单的文字评价")

    class Meta:
        ordering = ['-create_time']  # 默认按创建时间倒序排列

    def __str__(self):
        return f"Order {self.order_id} by {self.user.username}"
    def formatted_create_time(self):
        # 将 UTC 时间转换为北京时间 (UTC+8)
        beijing_time = self.create_time + timedelta(hours=8)
        return beijing_time.strftime("%Y-%m-%d %H:%M:%S")


class OrderItem(models.Model):
    STATUS_CHOICES = [
        ('pending_payment', '待支付'),
        ('in_preparation', '制作中'),
        ('cooked', '已制作完成'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),

    ]
    order = models.ForeignKey(
        'Order',
        on_delete=models.CASCADE,
        related_name='items',
        help_text="关联的父订单"
    )
    dish = models.ForeignKey(
        'Dish',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='order_items',
        help_text="关联的菜品"
    )
    quantity = models.PositiveIntegerField(help_text="菜品购买份数")
    customization = models.JSONField(
        null=True,
        blank=True,
        help_text="用户对菜品的个性化要求"
    )
    unit_price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="下单时的菜品快照价格"
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='pending_payment',
        help_text="菜品当前状态"
    )
    started_at = models.DateTimeField(null=True, blank=True, help_text="菜品制作开始时间")
    completed_at = models.DateTimeField(null=True, blank=True, help_text="菜品制作完成时间")

    class Meta:
        unique_together = ('order', 'dish')  # 同一订单中同一种菜品只能出现一次

    def __str__(self):
        return f"{self.quantity} x {self.dish.dish_name} in Order {self.order.order_id}"


class OrderImage(models.Model):
    order = models.ForeignKey(
        'Order',
        on_delete=models.CASCADE,
        related_name='images',
        help_text="关联的父订单"
    )
    image = models.ForeignKey(
        'Image',
        on_delete=models.CASCADE,
        related_name='order_images',
        help_text="关联的图片资源"
    )
    sort_order = models.SmallIntegerField(
        default=0,
        help_text="控制图片展示顺序，值越小越靠前"
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        help_text="图片上传的时间戳"
    )

    class Meta:
        unique_together = ('order', 'image')  # 联合唯一约束

    def __str__(self):
        return f"Image {self.image.image_id} for Order {self.order.order_id}"


class Employee(models.Model):
    """员工表 - 直接使用user_id作为主键"""
    EMPLOYMENT_STATUS_CHOICES = [
        ('active', '在职'),
        ('resigned', '离职'),
    ]

    # 直接使用user作为主键，不需要单独的employee_id
    user = models.OneToOneField(
        'User',
        on_delete=models.CASCADE,
        primary_key=True,
        related_name='employee_profile',
        help_text="关联的用户账户"
    )
    merchant = models.ForeignKey(
        'MerchantInfo',
        on_delete=models.CASCADE,
        related_name='employees',
        help_text="所属商家"
    )

    # 员工基本信息
    real_name = models.CharField(max_length=50, help_text="员工真实姓名")
    hire_date = models.DateField(help_text="入职日期")
    employment_status = models.CharField(
        max_length=10,
        choices=EMPLOYMENT_STATUS_CHOICES,
        default='active',
        help_text="在职状态"
    )

    # 工作时间安排
    work_start_time = models.TimeField(help_text="标准上班时间")
    work_end_time = models.TimeField(help_text="标准下班时间")

    # 工作安排 - 一周七天的上班状态
    monday_work = models.BooleanField(default=True, help_text="周一是否上班")
    tuesday_work = models.BooleanField(default=True, help_text="周二是否上班")
    wednesday_work = models.BooleanField(default=True, help_text="周三是否上班")
    thursday_work = models.BooleanField(default=True, help_text="周四是否上班")
    friday_work = models.BooleanField(default=True, help_text="周五是否上班")
    saturday_work = models.BooleanField(default=False, help_text="周六是否上班")
    sunday_work = models.BooleanField(default=False, help_text="周日是否上班")

    # 薪资相关
    base_daily_salary = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        help_text="基础日薪"
    )
    late_penalty_per_minute = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        help_text="迟到每分钟扣款"
    )
    early_leave_penalty_per_minute = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        help_text="早退每分钟扣款"
    )
    activity_bonus_per_count = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
        help_text="每次活动奖金"
    )

    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.real_name} ({self.user.username})"

    @property
    def employee_id(self):
        """为了兼容性，提供employee_id属性，实际返回user_id"""
        return self.user_id


class Attendance(models.Model):
    """员工考勤表"""
    attendance_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    employee = models.ForeignKey(
        'Employee',
        on_delete=models.CASCADE,
        related_name='attendances',
        help_text="关联员工"
    )
    work_date = models.DateField(help_text="工作日期")

    # 考勤时间记录
    scheduled_start = models.TimeField(help_text="计划上班时间")
    scheduled_end = models.TimeField(help_text="计划下班时间")
    actual_start = models.TimeField(null=True, blank=True, help_text="实际上班时间")
    actual_end = models.TimeField(null=True, blank=True, help_text="实际下班时间")

    notes = models.TextField(null=True, blank=True, help_text="备注信息")

    class Meta:
        unique_together = ('employee', 'work_date')
        ordering = ['-work_date']

    def __str__(self):
        return f"{self.employee.real_name} - {self.work_date}"


class EmployeeActivity(models.Model):
    """员工活动表"""
    ACTIVITY_TYPE_CHOICES = [
        ('serve_dish', '上菜'),
        ('cook_dish', '做菜'),
    ]

    activity_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    employee = models.ForeignKey(
        'Employee',
        on_delete=models.CASCADE,
        related_name='activities',
        help_text="执行活动的员工"
    )
    order_item = models.ForeignKey(
        'OrderItem',
        on_delete=models.CASCADE,
        related_name='employee_activities',
        help_text="关联的订单项"
    )
    activity_type = models.CharField(
        max_length=10,
        choices=ACTIVITY_TYPE_CHOICES,
        help_text="活动类型"
    )
    activity_time = models.DateTimeField(help_text="活动执行时间")

    class Meta:
        ordering = ['-activity_time']

    def __str__(self):
        return f"{self.employee.real_name} - {self.get_activity_type_display()}: {self.order_item.dish.dish_name}"


class LeaveRequest(models.Model):
    """请假表 - 简化版本，删除approver字段"""
    LEAVE_TYPE_CHOICES = [
        ('sick', '病假'),
        ('personal', '事假'),
        ('annual', '年假'),
    ]

    STATUS_CHOICES = [
        ('pending', '待审批'),
        ('approved', '已批准'),
        ('rejected', '已拒绝'),
    ]

    leave_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    employee = models.ForeignKey(
        'Employee',
        on_delete=models.CASCADE,
        related_name='leave_requests',
        help_text="申请请假的员工"
    )
    
    # 删除了 approver 字段，不再记录审批人信息
    
    leave_type = models.CharField(
        max_length=10,
        choices=LEAVE_TYPE_CHOICES,
        help_text="请假类型"
    )

    # 请假时间
    start_date = models.DateField(help_text="请假开始日期")
    end_date = models.DateField(help_text="请假结束日期")

    # 申请信息
    reason = models.TextField(help_text="请假原因")
    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='pending',
        help_text="审批状态"
    )

    # 审批信息（不记录审批人，只记录时间和备注）
    approval_time = models.DateTimeField(null=True, blank=True, help_text="审批时间")
    approval_notes = models.TextField(null=True, blank=True, help_text="审批备注")

    created_at = models.DateTimeField(auto_now_add=True, help_text="申请提交时间")

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.employee.real_name} - {self.get_leave_type_display()} ({self.start_date} ~ {self.end_date})"


class PerformanceRecord(models.Model):
    """绩效记录表 - 详细计算当日工资"""
    performance_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    employee = models.ForeignKey(
        'Employee',
        on_delete=models.CASCADE,
        related_name='performance_records',
        help_text="员工"
    )
    record_date = models.DateField(help_text="绩效记录日期")

    # 出勤状态
    is_work_day = models.BooleanField(default=True, help_text="是否应该上班")
    is_present = models.BooleanField(default=True, help_text="是否实际出勤")
    is_on_leave = models.BooleanField(default=False, help_text="是否请假")

    # 考勤时间统计（分钟）
    late_minutes = models.PositiveIntegerField(default=0, help_text="迟到分钟数")
    early_leave_minutes = models.PositiveIntegerField(default=0, help_text="早退分钟数")
    overtime_minutes = models.PositiveIntegerField(default=0, help_text="加班分钟数")
    work_minutes = models.PositiveIntegerField(default=0, help_text="实际工作分钟数")

    # 活动统计
    activity_count = models.PositiveIntegerField(default=0, help_text="当日活动次数")

    # 工资计算
    base_salary = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        help_text="基础日薪"
    )
    late_penalty = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        help_text="迟到扣款"
    )
    early_leave_penalty = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        help_text="早退扣款"
    )
    activity_bonus = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        help_text="活动奖金"
    )
    overtime_bonus = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0,
        help_text="加班费"
    )
    daily_total_salary = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        help_text="当日总工资"
    )

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('employee', 'record_date')
        ordering = ['-record_date']

    def __str__(self):
        return f"{self.employee.real_name} - {self.record_date} (¥{self.daily_total_salary})"


class SalaryRecord(models.Model):
    """工资记录表"""
    salary_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    employee = models.ForeignKey(
        'Employee',
        on_delete=models.CASCADE,
        related_name='salary_records',
        help_text="员工"
    )

    # 工资周期
    start_date = models.DateField(help_text="统计开始日期")
    end_date = models.DateField(help_text="统计结束日期")

    # 工资金额（基于绩效表汇总）
    total_salary = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="总工资"
    )

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-start_date']

    def __str__(self):
        return f"{self.employee.real_name} - {self.start_date} ~ {self.end_date} (¥{self.total_salary})"


class FranchiseApplication(models.Model):
    """加盟申请表（商家注册申请表）"""
    STATUS_CHOICES = [
        ('pending', '待审批'),
        ('approved', '已批准'),
        ('rejected', '已拒绝'),
    ]

    application_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # 申请人信息
    applicant = models.ForeignKey(
        'User',
        on_delete=models.CASCADE,
        related_name='franchise_applications',
        help_text="申请人用户"
    )
    
    # 商家信息（与MerchantInfo字段一致）
    shop_name = models.CharField(max_length=100, help_text="商家门店的公开显示名称")
    location = models.CharField(max_length=255, help_text="商家门店的公开地址")
    business_hours = models.CharField(max_length=255, null=True, blank=True, help_text="商家营业时间配置")
    contact_info = models.CharField(max_length=255, help_text="商家联系方式信息")
    introduction = models.TextField(
        null=True,
        blank=True,
        help_text="商家自我介绍，用于展示门店特色、服务内容或品牌故事"
    )
    
    # 审批状态
    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='pending',
        help_text="审批状态"
    )
    
    # 审批相关信息
    approval_time = models.DateTimeField(null=True, blank=True, help_text="审批时间")
    approval_notes = models.TextField(null=True, blank=True, help_text="审批备注")
    
    # 申请时间
    created_at = models.DateTimeField(auto_now_add=True, help_text="申请提交时间")
    updated_at = models.DateTimeField(auto_now=True, help_text="申请更新时间")

    class Meta:
        ordering = ['-created_at']  # 按申请时间倒序排列
        
    def __str__(self):
        return f"{self.shop_name} - {self.get_status_display()} ({self.applicant.username})"


class FranchiseApplicationImage(models.Model):
    """加盟申请图片关联表"""
    application = models.ForeignKey(
        'FranchiseApplication',
        on_delete=models.CASCADE,
        related_name='application_images',
        help_text="所属加盟申请"
    )
    image = models.ForeignKey(
        'Image',
        on_delete=models.CASCADE,
        related_name='franchise_application_images',
        help_text="关联的图片资源"
    )
    sort_order = models.SmallIntegerField(
        default=0,
        help_text="控制图片展示顺序，值越小越靠前"
    )
    is_cover = models.BooleanField(
        default=False,
        help_text="是否为封面图，同一申请最多一个 TRUE"
    )

    class Meta:
        unique_together = ('application', 'image')  # 联合唯一约束
        ordering = ['sort_order']  # 默认按排序序号升序排列

    def __str__(self):
        return f"Application {self.application.shop_name} Image {self.image.image_id}"